import {
  Controller,
  Get,
  Post,
  Body,
  UseInterceptors,
  UploadedFile,
  UploadedFiles,
  Query,
  Res,
} from '@nestjs/common';
import { UploaderService } from './uploader.service';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import type { Response, query } from 'express';
import { join } from 'path';
import { zip } from 'compressing';
import { ApiTags } from '@nestjs/swagger';
import { IPaginationFormWithCondition } from 'types/requestParams';
import { Public } from 'src/decorations/public.decorator';

@ApiTags('上传')
@Controller('uploader')
export class UploaderController {
  constructor(private readonly uploaderService: UploaderService) { }

  // 单张文件上传
  @Post('single')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file, @Query() req) {
    return this.uploaderService.uploadSingle(file, req)
  }

  // 根据图片名称和分类查找
  @Post('find')
  findByCondition(@Body() body: IPaginationFormWithCondition) {
    return this.uploaderService.find(body)
  }

  // 修改图片信息
  @Post('updateImageName')
  updateName(@Body() body) {
    return this.uploaderService.update(body)
  }

  // 删除图片
  @Get('delImg')
  delOne(@Query() req) {
    return this.uploaderService.delImg(req.id)
  }
  
  // 硬删除文件
  @Get('delFileHard')
  delOneFileHard(@Query() req) {
    return this.uploaderService.delFileHard(req.id)
  }

  // 新增图片分类
  @Post('createCategory')
  createCategory(@Body() body) {
    return this.uploaderService.createCategory(body)
  }

  // 获取所有图片分类
  @Get('categories')
  getAllCategory() {
    return this.uploaderService.getAllCategory()
  }

  // 删除分类
  @Get("delCategory")
  delCategory(@Query() req) {
    return this.uploaderService.delCategory(req.id)
  }

  // 修改分类信息
  @Post('updateCategory')
  updateCategory(@Body() body) {
    return this.uploaderService.updateCategory(body)
  }

  // 批量上传文件
  @Public()
  @Post('batchUpload')
  @UseInterceptors(FilesInterceptor('file'))
  uploadBatch(@UploadedFiles() files, @Query() req) {
    return this.uploaderService.uploadBatch(files,req)
  }

  // 导出图片
  @Public()
  @Get('export')
  download(@Query() query, @Res() res: Response) {
    const url = join(__dirname, '../statics/1698398705143.jpg');
    console.log(url);
    res.download(url)
    // res.send('ok')
  }

  // 导出压缩包
  // // 使用流的方式下载文件，需要前端配合，比如使用 responseType: bolb，下载的是压缩包
  // @Get('stream')
  // async downloadZip(@Res() res: Response) {
  //   const url = join(__dirname, '../images/1677746740445.jpg');
  //   const tarStream = new zip.Stream()
  //   await tarStream.addEntry(url);
  //   res.setHeader('Content-Type', 'application/octet-stream'); // 固定
  //   res.setHeader(   // 固定
  //     'Content-Disposition',
  //     `attachment; filename=xiaoman`,
  //   );
  //   tarStream.pipe(res)
  // }
}
